<template>
  <div class="max-w-xl p-4 mx-auto">
    <h2 class="mb-4 text-xl font-bold">Base64 编码/解码工具</h2>
    <textarea v-model="input" rows="5" class="w-full p-2 mb-4 border rounded" placeholder="请输入文本或 Base64..."></textarea>
    <div class="flex gap-2 mb-4">
      <button @click="encode" class="px-4 py-2 text-white bg-blue-500 rounded">编码</button>
      <button @click="decode" class="px-4 py-2 text-white bg-gray-500 rounded">解码</button>
      <button @click="clearAll" class="px-4 py-2 text-gray-700 bg-gray-200 rounded">清空</button>
    </div>
    <div v-if="output" class="p-2 text-sm break-all border rounded">
      {{ output }}
    </div>
    <div v-if="error" class="mt-2 text-red-500">{{ error }}</div>
  </div>
</template>

<script setup lang="ts">
import { ref } from 'vue'
const input = ref('')
const output = ref('')
const error = ref('')

function encode() {
  try {
    error.value = ''
    output.value = btoa(unescape(encodeURIComponent(input.value)))
  } catch (e) {
    error.value = '编码失败，请检查输入内容'
    output.value = ''
  }
}
function decode() {
  try {
    error.value = ''
    output.value = decodeURIComponent(escape(atob(input.value)))
  } catch (e) {
    error.value = '解码失败，请检查输入内容'
    output.value = ''
  }
}
function clearAll() {
  input.value = ''
  output.value = ''
  error.value = ''
}
</script>